import React from 'react';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import './index.less';
/**
 * @description 富文本编辑器
 */
export default class RichText extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty(),
    };
  }

  shouldComponentUpdate(aaaa, vvvvv) {
    // 转换成HTML格式
    const editorContent = draftToHtml(
      convertToRaw(this.state.editorState.getCurrentContent()),
    );
    // this.props.saveSys({roomnotes: editorContent})
    console.log('shouldComponentUpdate', aaaa, vvvvv, editorContent);
    if (editorContent == '<p></p>') {
      return false;
    }
    return true;
  }
  componentWillReceiveProps(nextProps) {
    console.log('componentWillReceiveProps', nextProps, this.props);
    if (nextProps && nextProps.value) {
      const contentBlock = htmlToDraft(nextProps.value);
      const contentState = ContentState.createFromBlockArray(
        contentBlock.contentBlocks,
      );
      const editorState = EditorState.createWithContent(contentState);
      this.setState({ editorState });
    }
    // if (this.props.getSysResult!==nextProps.getSysResult && nextProps.getSysResult.data) {
    //   // 匹配富文本编辑器格式，回显保存的内容
    //   const contentBlock = htmlToDraft(nextProps.getSysResult.data.roomnotes);
    //   if (contentBlock) {
    //     const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
    //     const editorState = EditorState.createWithContent(contentState);
    //     this.setState({ editorState })
    //   }
    // }
  }

  //富文本内容改变时
  onEditorStateChange = (editorState) => {
    this.setState({ editorState });
  };
  getInputData = () => {
    const { editorState } = this.state;
    return draftToHtml(convertToRaw(editorState.getCurrentContent())); //获取富文本内容
  };
  //上传图片
  uploadImageCallBack = (file) => {
    let token = localStorage.getItem('token');
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open('POST', '/api/common/upload');
      xhr.setRequestHeader('Authorization', `Bearer ${token}`);
      const data = new FormData();
      data.append('image', file);
      xhr.send(data);
      xhr.addEventListener('load', () => {
        const response = JSON.parse(xhr.responseText);
        const { status, data } = response;
        console.log('response=======>', response, status, data);
        if (status === 0) {
          resolve({ data: { link: data } });
        }
      });
      xhr.addEventListener('error', () => {
        const error = JSON.parse(xhr.responseText);
        reject(error);
      });
    });
  };
  render() {
    const { editorState } = this.state;
    return (
      <div>
        <Editor
          localization={{ locale: 'zh' }}
          editorState={editorState}
          wrapperClassName="editor-wrapper"
          editorClassName="editor-editor"
          editorStyle={{
            border: '1px solid rgba(0, 0, 0, 0.65)',
            minHeight: '100px',
            lineHeight: '0.1rem',
            textIndent: '2rem',
          }}
          onEditorStateChange={this.onEditorStateChange}
          toolbar={{
            // inline: { inDropdown: true },
            // list: { inDropdown: true },
            // textAlign: { inDropdown: true },
            // link: { inDropdown: true },
            // history: { inDropdown: true },
            image: {
              uploadCallback: this.uploadImageCallBack,
              alt: { present: true, mandatory: true },
            },
          }}
        />
      </div>
    );
  }
}
